package net.comm.common;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;

import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


public class Email {

	  private MimeMessage mimeMsg;  
	   private Session session;  
	   private Properties props;  
	   private boolean needAuth;  
	   private String username;  
	   private String password;  
	   private Multipart mp;  
	     
	  public Email(String smtp)  
	  {  
	      needAuth = false;  
	      username = "";  
	      password = "";  
	      setSmtpHost(smtp);  
	      createMimeMessage();  
	  }  
	  
	  //设置发送邮件的主机(JavaMail需要Properties来创建一个session对象。它将寻找字符串"mail.smtp.host"，属性值就是发送邮件的主机);
	  public void setSmtpHost(String hostName)  
	  {  
//	      System.out.println("设置系统属性：mail.smtp.host = " + hostName);  
	      if(props == null)  
	          props = System.getProperties();  
	      props.put("mail.smtp.host", hostName);  
	  }  
	  
	  //(这个Session类代表JavaMail 中的一个邮件session. 每一个基于 JavaMail的应用程序至少有一个session但是可以有任意多的session。 在这个例子中, Session对象需要知道用来处理邮件的SMTP 服务器。);
	  public boolean createMimeMessage()  
	  {  
	      try 
	      {  
//	          System.out.println("准备获取邮件会话对象！");  
	          session = Session.getDefaultInstance(props, null);  
	      }  
	      catch(Exception e)  
	      {  
	          System.err.println("获取邮件会话对象时发生错误！" + e);  
	          return false;  
	      }  
//	      System.out.println("准备创建MIME邮件对象！");  
	      try 
	      {  
	          mimeMsg = new MimeMessage(session);  
	          mp = new MimeMultipart();  
	      }  
	      catch(Exception e)  
	      {  
	          System.err.println("创建MIME邮件对象失败！" + e);  
	          return false;  
	      }  
	      return true;  
	  }  
	  
	  //设置SMTP的身份认证；
	  public void setNeedAuth(boolean need)  
	  {  
//	      System.out.println("设置smtp身份认证：mail.smtp.auth = " + need);  
	      if(props == null)  
	          props = System.getProperties();  
	      if(need)  
	          props.put("mail.smtp.auth", "true");  
	      else 
	          props.put("mail.smtp.auth", "false");  
	  }  
	  
	  //设置用户名和密码；
	  public void setNamePass(String name, String pass)  
	  {  
//	      System.out.println("程序得到用户名与密码");  
	      username = name;  
	      password = pass;  
	  }  
	  
	  //设置邮件主题；
	  public boolean setSubject(String mailSubject)  
	  {  
//	      System.out.println("设置邮件主题！");  
	      try 
	      {  
	          mimeMsg.setSubject(mailSubject);  
	      }  
	      catch(Exception e)  
	      {  
	          System.err.println("设置邮件主题发生错误！");  
	          return false;  
	      }  
	      return true;  
	  }  
	  
	  //设置邮件内容；
	  public boolean setBody(String mailBody)  
	  {  
	      try 
	      {  
//	          System.out.println("设置邮件体格式");  
	    	  //删除原有的内容
	          int len = mp.getCount();
	          for(int i=0; i<len; i++){
	        	  mp.removeBodyPart(i);
	          }
	          //添加新内容
	    	  BodyPart bp = new MimeBodyPart();  
	          bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=UTF-8>" + mailBody, "text/html;charset=UTF-8");  
	          
	          mp.addBodyPart(bp);  
	      }  
	      catch(Exception e)  
	      {  
	          System.err.println("设置邮件正文时发生错误！" + e);  
	          return false;  
	      }  
	      return true;  
	  }  
	  
	  //增加发送附件；
	  public boolean addFileAffix(String filename)  
	  {  
//	      System.out.println("增加邮件附件：" + filename);  
	      try 
	      {  
	          BodyPart bp = new MimeBodyPart();  
	          FileDataSource fileds = new FileDataSource(filename);  
	          bp.setDataHandler(new DataHandler(fileds));  
	          bp.setFileName(fileds.getName());  
	          mp.addBodyPart(bp);  
	      }  
	      catch(Exception e)  
	      {  
	          System.err.println("增加邮件附件：" + filename + "发生错误！" + e);  
	          return false;  
	      }  
	      return true;  
	  }  
	  
	  //设置发件人地址；
	  public boolean setFrom(String addr,String from)  
	  {  
//	      System.out.println("设置发信人！");  
	      try 
	      {  
	    	  InternetAddress fromAddress = new InternetAddress(addr,from,"GBK");
	          mimeMsg.setFrom(fromAddress);  
	      }  
	      catch(Exception e)  
	      {  
	          return false;  
	      }  
	      return true;  
	  }  
	  
	  //设置收件人地址；
	  public boolean setTo(String to)  
	  {  
//	      System.out.println("设置收信人");  
	      if(to == null)  
	          return false;  
	      try 
	      {  
	          mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));  
	      }  
	      catch(Exception e)  
	      {  
	          return false;  
	      }  
	      return true;  
	  }  
	  
	  //发送附件；
	  public boolean setCopyTo(String copyto)  
	  {  
//	      System.out.println("发送附件到");  
	      if(copyto == null)  
	          return false;  
	      try 
	      {  
	          mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(copyto));  
	      }  
	      catch(Exception e)  
	      {  
	          return false;  
	      }  
	      return true;  
	  }  
	  
	  //发送邮件；
	  public boolean sendout()  
	  {  
	      try 
	      {  
	          mimeMsg.setContent(mp);  
	          mimeMsg.saveChanges();  
//	          System.out.println("正在发送邮件....");  
	          Session mailSession = Session.getInstance(props, null);  
	          Transport transport = mailSession.getTransport("smtp");  
	          transport.connect((String)props.get("mail.smtp.host"), username, password);  
	          transport.sendMessage(mimeMsg, mimeMsg.getRecipients(javax.mail.Message.RecipientType.TO));  
//	          System.out.println("发送邮件成功！");  
	          transport.close();  
	      }  
	      catch(Exception e)  
	      {  
	          System.err.println("邮件发送失败！" + e.getMessage());  
	          e.printStackTrace();  
	          return false;  
	      }  
	      return true;  
	  }  


	  public static void main(String[] args) {  
	    
	      Email themail = new Email(GlbFinal.EMAIL_SMTP);  
	         String mailbody = "尊敬的......" ;  
	         
	             themail.setNeedAuth(true);  
	             themail.setSubject("你好");  
	             themail.setBody(mailbody);  
	             themail.setTo("hcgong2003@163.com");  	//"收件人地址"
	             themail.setFrom(GlbFinal.EMAIL_ADDR,GlbFinal.EMAIL_FRNAME);					//"发件人地址"
//	             themail.addFileAffix(" ");			//附件文件路径,例如：C:/222.jpg,*注；"/"的写法；
	             themail.setNamePass(GlbFinal.EMAIL_FRUSER, GlbFinal.EMAIL_FRUSERPSD);  			//"用户名","密码"
	             themail.sendout();  

	  
	  
	  } 

	}
